package com.code.test.first.backtracking;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * TODO 再Review
 * https://github.com/youngyangyang04/leetcode-master/blob/master/problems/0131.%E5%88%86%E5%89%B2%E5%9B%9E%E6%96%87%E4%B8%B2.md
 * 给定一个字符串 s，将 s 分割成一些子串，使每个子串都是回文串。
 *
 * 返回 s 所有可能的分割方案。
 *
 * 示例: 输入: "aab" 输出: [ ["aa","b"], ["a","a","b"] ]
 */
public class Code131 {

    public static void main(String[] args) {
        List<List<String>> ret = partition("aab");
        System.out.println(ret);
    }

    static List<List<String>> list = new ArrayList<>();

    static Deque<String> path = new LinkedList<>();

    public static List<List<String>> partition(String s) {
        backtracking(s, 0);
        return list;
    }

    public static void backtracking(String s, int startIndex) {
        if (startIndex > s.length()) {
            list.add(new ArrayList<>(path));
            return;
        }

        for (int i = startIndex; i < s.length(); i++) {
            //判断当前开始的字串是否为回文串
            if (isPalindrome(s, startIndex, i)) {
                String str = s.substring(startIndex, i + 1);
                path.add(str);
            } else {
                continue;
            }

            backtracking(s, i + 1);
            path.removeLast();
        }
    }

    private static boolean isPalindrome(String s, int start, int end) {
        for (int i = start, j = end; i < j; i++, j--) {
            if (s.charAt(i) != s.charAt(j)) {
                return false;
            }
        }
        return true;

    }

}